package com.zero.flutter_gromore_ads.load;


import static com.zero.flutter_gromore_ads.PluginDelegate.KEY_LOGO;
import static com.zero.flutter_gromore_ads.PluginDelegate.KEY_TIMEOUT;
import static com.zero.flutter_gromore_ads.PluginDelegate.PRELOAD;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.CSJAdError;
import com.bytedance.sdk.openadsdk.CSJSplashAd;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationAdEcpmInfo;
import com.zero.flutter_gromore_ads.PluginDelegate;
import com.zero.flutter_gromore_ads.event.AdEcpmEvent;
import com.zero.flutter_gromore_ads.event.AdErrorEvent;
import com.zero.flutter_gromore_ads.event.AdEvent;
import com.zero.flutter_gromore_ads.event.AdEventAction;
import com.zero.flutter_gromore_ads.event.AdEventHandler;
import com.zero.flutter_gromore_ads.page.AdSplashActivity;
import com.zero.flutter_gromore_ads.page.BaseAdPage;
import com.zero.flutter_gromore_ads.utils.UIUtils;

import io.flutter.plugin.common.MethodCall;

/**
 * 开屏广告
 */
public class SplashAdLoad extends BaseAdPage implements TTAdNative.CSJSplashAdListener, CSJSplashAd.SplashAdListener {
    private final String TAG = SplashAdLoad.class.getSimpleName();
    // 开屏广告
    public CSJSplashAd gmSplashAd;
    // logo
    private String logo;
    // 超时时间
    double timeout = 3.5;

    // 预加载
    boolean preload = false;
    // 加载完成
    public boolean isLoaded = false;
    // 展示中
    public boolean isDisplay = false;
    // 广告展示中
    public boolean isShow = false;

    @Override
    public void loadAd(MethodCall call) {
        logo = call.argument(KEY_LOGO);
        timeout = call.argument(KEY_TIMEOUT);
        preload = call.argument(PRELOAD);
        int absTimeout = (int) (timeout * 1000);
        // 判断是否有 Logo
        boolean hasLogo = !TextUtils.isEmpty(logo);
        int width = (int) UIUtils.getScreenWidthInPx(activity);
        int height = UIUtils.getRealHeight(activity);
        // 判断最终的 Logo 是否显示
        if (hasLogo) {
            // 显示 Logo 高度去掉 Logo 的高度
            height = height - 192;
        }
        // 创建开屏广告
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(posId)
                .setImageAcceptedSize(width, height) // 单位是px
                .build();
        // 加载广告
        adLoader.loadSplashAd(adSlot, this, absTimeout);
    }

    /**
     * 跳转到 Activity
     */
    public void goActivity() {
        if (gmSplashAd == null || !gmSplashAd.getMediationManager().isReady()) {
            Log.e(TAG, "页面跳转失败，请现在调用 preloadSplashAd 进行预加载");
            return;
        }
        Intent intent = new Intent(activity, AdSplashActivity.class);
        intent.putExtra(KEY_LOGO, logo);
        activity.startActivity(intent);
        // 设置进入动画
        activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
        isDisplay = true;
    }

    /**
     * 完成广告，退出开屏页面
     */
    public void finishPage() {
        // 销毁
        if (gmSplashAd != null && gmSplashAd.getMediationManager() != null) {
            gmSplashAd.setSplashAdListener(null);
            gmSplashAd.getMediationManager().destroy();
            gmSplashAd = null;
        }
        Intent intent = new Intent("BR_AdSplashLoadActivity");
        // 可以放一些数据在Intent
        LocalBroadcastManager.getInstance(activity).sendBroadcast(intent);
        // 清空插件持有对象
        PluginDelegate.getInstance().splashAdLoad = null;
        preload = false;
        isLoaded = false;
        isDisplay = false;
        isShow = false;
    }


    @Override
    public void onSplashLoadSuccess(CSJSplashAd csjSplashAd) {
        Log.d(TAG, "onSplashLoadSuccess");
        AdEventHandler.getInstance().sendEvent(new AdEvent(this.posId, AdEventAction.onAdLoaded));
        gmSplashAd = csjSplashAd;
        // 不是预加载则加载完毕就展示
        if (!preload) {
            goActivity();
        } else {
            isLoaded = true;
        }
    }

    @Override
    public void onSplashLoadFail(CSJAdError adError) {
        Log.e(TAG, "onSplashLoadFail code:" + adError.getCode() + " msg:" + adError.getMsg());
        AdEventHandler.getInstance().sendEvent(new AdErrorEvent(this.posId, adError.getCode(), adError.getMsg()));
        finishPage();
    }

    @Override
    public void onSplashRenderSuccess(CSJSplashAd csjSplashAd) {
        Log.d(TAG, "onSplashRenderSuccess");
        // 加载事件
        AdEventHandler.getInstance().sendEvent(new AdEvent(this.posId, AdEventAction.onAdPresent));
        gmSplashAd = csjSplashAd;
        gmSplashAd.setSplashAdListener(this);
    }

    @Override
    public void onSplashRenderFail(CSJSplashAd csjSplashAd, CSJAdError adError) {
        Log.e(TAG, "onSplashRenderFail code:" + adError.getCode() + " msg:" + adError.getMsg());
        if(!isShow){
            AdEventHandler.getInstance().sendEvent(new AdErrorEvent(this.posId, adError.getCode(), adError.getMsg()));
            finishPage();
        }
    }

    @Override
    public void onSplashAdShow(CSJSplashAd csjSplashAd) {
        Log.d(TAG, "onAdShow");
        AdEventHandler.getInstance().sendEvent(new AdEvent(this.posId, AdEventAction.onAdExposure));
        // 添加 Ecmp 事件
        if (gmSplashAd != null) {
            MediationAdEcpmInfo adEcpmInfo = gmSplashAd.getMediationManager().getShowEcpm();
            AdEcpmEvent ecpmEvent = new AdEcpmEvent(this.posId, AdEventAction.onAdEcpm, adEcpmInfo);
            AdEventHandler.getInstance().sendEvent(ecpmEvent);
        }
    }

    @Override
    public void onSplashAdClick(CSJSplashAd csjSplashAd) {
        Log.d(TAG, "onAdClicked");
        AdEventHandler.getInstance().sendEvent(new AdEvent(this.posId, AdEventAction.onAdClicked));
        finishPage();
    }

    @Override
    public void onSplashAdClose(CSJSplashAd csjSplashAd, int i) {
        Log.d(TAG, "onSplashAdClose");
        AdEventHandler.getInstance().sendEvent(new AdEvent(this.posId, AdEventAction.onAdClosed));
        finishPage();
    }


}